package com.seckillpro.seckill_pro.rabbtmq;

import cn.hutool.json.JSONUtil;
import com.seckillpro.seckill_pro.pojo.SecKillMessage;
import com.seckillpro.seckill_pro.pojo.TSecKillOrder;
import com.seckillpro.seckill_pro.pojo.TUser;
import com.seckillpro.seckill_pro.service.ITGoodsService;
import com.seckillpro.seckill_pro.service.ITOrderService;
import com.seckillpro.seckill_pro.vo.GoodsVo;
import com.seckillpro.seckill_pro.vo.RespBean;
import com.seckillpro.seckill_pro.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Package: com.seckillpro.seckill_pro.rabbtmq
 * @ClassName: MQReceiver
 * @Author: lyx
 * @CreateTime: 2021/3/26 17:18
 * @Description:
 */

@Slf4j
@Service
public class MQReceiver {

//    @RabbitListener(queues = "queue")
//    public void receive(Object msg) {
//        log.info("接收消息 ：" + msg);
//
//    }

    @Autowired
    private ITGoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ITOrderService orderService;

    /**
     * 下单操作
     *
     * @param message
     */
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {

        log.info("message:" + message);
        SecKillMessage secKillMessage = JSONUtil.toBean(message, SecKillMessage.class);

        Long goodId = secKillMessage.getGoodId();
        TUser user = secKillMessage.getUser();

        GoodsVo goodsVo = goodsService.findGoodsVoByGoodId(goodId);

        if (goodsVo.getStockCount() < 1) {
            return;
        }

        //判断是否重复抢购
        TSecKillOrder secKillOrder =
                (TSecKillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodId);

        if (secKillOrder != null) {
            return;
        }

        //下单操作
        orderService.secKill(user, goodsVo);

    }

}
